package org.ftc.dao;

import java.util.Iterator;
import java.util.List;

import org.ftc.domain.RoleAuth;
import org.ftc.form.RoleAuthForm;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

@Repository
public class RoleAuthDao extends CurrentDao<RoleAuth, String> {

	@Override
	public RoleAuth load(String id) {
		return super.load(id);
	}

	@Override
	public RoleAuth get(String id) {
		return super.get(id);
	}

	@Override
	public synchronized boolean save(RoleAuth entity) {
		return super.save(entity);
	}

	@Override
	public synchronized boolean saveOrUpdate(RoleAuth entity) {
		return super.saveOrUpdate(entity);
	}

	@Override
	public synchronized boolean update(RoleAuth entity) {
		return super.update(entity);
	}

	@Override
	public synchronized boolean delete(RoleAuth entity) {
		return super.delete(entity);
	}

	@Override
	public synchronized boolean delete(String id) {
		return super.delete(id);
	}

	@Override
	public List<RoleAuth> findPage(int offset, int pageSize) {
		return super.findPage(offset, pageSize);
	}

	@Override
	public List<RoleAuth> findAll() {
		return super.findAll();
	}

	@Override
	public long countAll() {
		return super.countAll();
	}

	@SuppressWarnings("unchecked")
	public List<RoleAuth> findPage(RoleAuthForm form, int offset, int pageSize) {
		try {
			Criteria criteria = getSession().createCriteria(RoleAuth.class);
			criteriaWsql(form, criteria);
			criteriaSort(form, criteria);
			criteria.setFirstResult(offset);
			criteria.setMaxResults(pageSize);
			List<RoleAuth> list = (List<RoleAuth>) criteria.list();
			return list;
		} catch (Exception e) {
			getLog().error(e.toString());
			return null;
		}
	}

	public long count(RoleAuthForm form) {
		try {
			Criteria criteria = getSession().createCriteria(RoleAuth.class);
			criteria.setProjection(Projections.rowCount());
			criteriaWsql(form, criteria);
			return (Long) criteria.uniqueResult();
		} catch (Exception e) {
			getLog().error(e.toString());
			return 0;
		}
	}

	@SuppressWarnings("unchecked")
	public RoleAuth getByAuthName(String name) {
		try {
			Criteria criteria = getSession().createCriteria(RoleAuth.class);
			criteria.add(Restrictions.eq("authName", name));
			List<RoleAuth> list = criteria.list();
			for (Iterator<RoleAuth> it = list.iterator(); it.hasNext();)
				return (RoleAuth) it.next();
			return null;
		} catch (Exception e) {
			return null;
		}
	}

	private void criteriaWsql(RoleAuthForm form, Criteria criteria) {
		if (form.getAuthName() != null && form.getAuthName().length() > 0)
			criteria.add(Restrictions.like("authName", "%" + form.getAuthName() + "%"));
	}

}
